import java.util.PriorityQueue;
import java.util.Timer;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-16
 * Time: 22:55
 */
class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    private long time;
    public MyTimerTask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }
    public long getTime(){
        return time;//返回任务执行时间
    }
    public void run(){
        runnable.run();
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);
    }
}
class MyTimer{
    Object locker=new Object();
    private PriorityQueue<MyTimerTask> queue =new PriorityQueue<>();
    public MyTimer(){
        Thread t=new Thread(()->{
            while (true) {
                synchronized (this) {
                    if (queue.size() == 0) {
                        try {
                            this.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    MyTimerTask task = queue.peek();
                    long curTime = System.currentTimeMillis();
                    if (curTime <task.getTime()) {
                        try {
                        this.wait(task.getTime()-curTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    }else{
                        task.run();
                        queue.poll();
                    }


                }
            }
        });
        t.start();
    }
    public void schedule(Runnable runnable,long delay) {
        MyTimerTask myTimerTask = new MyTimerTask(runnable, delay);
        synchronized (this) {
            queue.offer(myTimerTask);
            this.notify();
        }





    }
}
public class Demo2 {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 5000");
            }
        },5000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 10000");
            }
        },10000);
    }
}
